﻿using System.Security.Cryptography;
using System.Text;

namespace Common
{
    /// <summary>
    /// 安全帮助
    /// </summary>
    public static class SecurityHelper
    {
        /// <summary>
        /// 生成盐(16进制,进制*2位)
        /// </summary>
        /// <param name="saltSize"></param>
        /// <returns></returns>
        public static string GenerateSaltHex(int saltSize = 16)
        {
            byte[] saltByte = new byte[saltSize];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(saltByte);
            }
            StringBuilder sb = new();
            foreach (byte b in saltByte)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            return sb.ToString();
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static string MD5Encrypt(string rawData)
        {
            using MD5 mD5 = MD5.Create();
            byte[] rawByte = mD5.ComputeHash(Encoding.UTF8.GetBytes(rawData));
            StringBuilder builder = new();
            for (int i = 0; i < rawByte.Length; i++)
            {
                builder.Append(rawByte[i].ToString("x2"));
            }
            return builder.ToString();
        }
        /// <summary>
        /// SHA256加密
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static string SHA256Encrypt(string rawData)
        {
            using SHA256 sHA256 = SHA256.Create();
            byte[] rawByte = sHA256.ComputeHash(Encoding.UTF8.GetBytes(rawData));
            StringBuilder builder = new();
            for (int i = 0; i < rawByte.Length; i++)
            {
                builder.Append(rawByte[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }
}
